<template>
  <div class="app-container task-arrangement-page">
   
    <!-- 搜索表单 -->
    <div class="search-container" v-show="showSearch">
      <el-form :model="queryParams" ref="queryRef" label-width="100px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="老人姓名" prop="elderlyName">
              <el-select
                v-model="queryParams.elderlyName"
                placeholder="请选择"
                filterable
                clearable
                class="search-select"
              >
                <el-option
                  v-for="item in elderlyOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="护理员姓名" prop="caregiverName">
              <el-select
                v-model="queryParams.caregiverName"
                placeholder="请选择"
                clearable
                class="search-select"
              >
                <el-option
                  v-for="item in caregiverOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="护理项目" prop="nursingItemName">
              <el-select
                v-model="queryParams.nursingItemName"
                placeholder="请选择"
                clearable
                class="search-select"
              >
                <el-option
                  v-for="item in nursingItemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="期望服务时间" prop="expectedServiceTime">
              <el-date-picker
                v-model="queryParams.expectedServiceTime"
                type="daterange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD"
                class="search-date-picker"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="请选择"
                clearable
                class="search-select"
                @change="handleStatusChange"
              >
                <el-option label="全部" value="" />
                <el-option label="待执行" value="待执行" />
                <el-option label="已执行" value="已执行" />
                <el-option label="已取消" value="已取消" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label=" " class="form-buttons">
              <el-button type="default" @click="resetQuery" class="reset-btn">重置</el-button>
              <el-button type="primary" @click="handleQuery" class="search-btn">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 状态筛选和操作按钮 -->
    <el-row :gutter="10" class="toolbar-row">
      <el-col :span="12">
        <el-radio-group v-model="queryParams.status" @change="handleStatusChange" class="status-radio-group">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="待执行">待执行</el-radio-button>
          <el-radio-button label="已执行">已执行</el-radio-button>
          <el-radio-button label="已取消">已取消</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="12" class="text-right">
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        <el-button
          type="warning"
          plain
          icon="Calendar"
          @click="handleTodayPending"
          class="action-btn today-pending-btn"
        >
          <span style="font-weight: 600;">今日待执行</span>
        </el-button>
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:arrangement:add']"
          class="action-btn"
        >新增</el-button>
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:arrangement:edit']"
          class="action-btn"
        >修改</el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:arrangement:remove']"
          class="action-btn"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:arrangement:export']"
          class="action-btn"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table 
      v-loading="loading" 
      :data="arrangementList" 
      @selection-change="handleSelectionChange" 
      empty-text="暂无数据"
      class="task-arrangement-table"
      stripe
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="80" />
      <el-table-column label="老人姓名" align="center" prop="elderly_name" width="100" />
      <el-table-column label="床位号" align="center" prop="bed_no" width="80" />
      <el-table-column label="护理项目" align="center" width="120" prop="nursing_item_name">
        <template #default="scope">
          <span>{{ scope.row.nursing_item_name || '无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" align="center" width="120">
        <template #default="scope">
          <el-tag :type="getProjectTypeStyle(scope.row.project_type)" effect="plain">
            {{ scope.row.project_type }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="护理员" align="center" width="100">
        <template #default="scope">
          <span>{{ scope.row.executor_name || '未分配' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="期望服务时间" align="center" prop="expected_service_time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expected_service_time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="100">
        <template #default="scope">
          <span>{{ scope.row.project_type === '护理计划内' ? '系统' : (scope.row.creator_name || '未知') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="create_time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联单据" align="center" width="150">
        <template #default="scope">
          <span v-if="scope.row.order_no && scope.row.order_no !== '无'">
            {{ scope.row.order_no }}
          </span>
          <span v-else class="text-muted">无</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)" effect="plain">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="danger" 
            icon="Close" 
            @click="handleCancel(scope.row)"
            v-if="scope.row.status === '待执行'"
            v-hasPermi="['system:arrangement:edit']"
          >取消</el-button>
          <el-button 
          link 
          type="primary" 
           icon="View" 
          @click="handleView(scope.row)"
          v-hasPermi="['system:arrangement:query']"
          >查看</el-button>
          <el-button 
            link 
            type="success" 
            icon="Check" 
            @click="handleExecute(scope.row)"
            v-if="scope.row.status === '待执行'"
            v-hasPermi="['system:arrangement:edit']"
          >执行</el-button>
          <el-button 
            link 
            type="warning" 
            icon="Refresh" 
            @click="handleReschedule(scope.row)"
            v-if="scope.row.status === '待执行'"
            v-hasPermi="['system:arrangement:edit']"
          >改期</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 数据统计 -->
    <div v-if="!loading && arrangementList.length > 0" class="data-stats">
      <el-alert 
        :title="`共找到 ${total} 条任务数据，当前显示第 ${queryParams.pageNum} 页，共 ${Math.ceil(total / queryParams.pageSize)} 页`"
        type="info" 
        :closable="false"
        show-icon
      />
    </div>
    
    <!-- 分页 -->
    <pagination
      class="task-arrangement-pagination"
      v-show="total>0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="handlePagination"
    />

    <!-- 执行记录对话框 -->
    <el-dialog title="新增执行记录" v-model="executeDialogOpen" width="500px" append-to-body>
      <el-form ref="executeRef" :model="executeForm" :rules="executeRules" label-width="100px">
        <el-form-item label="执行时间" prop="executionTime">
          <el-date-picker
            v-model="executeForm.executionTime"
            type="datetime"
            placeholder="请选择执行时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="执行图片" prop="executionImage">
          <div class="image-upload-container">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="uploadHeaders"
              :on-success="handleImageSuccess"
              :on-error="handleImageError"
              :before-upload="beforeImageUpload"
              :show-file-list="false"
              accept="image/png,image/jpg,image/jpeg"
            >
              <div class="upload-area" v-if="!executeForm.executionImage">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击上传图片</div>
                <div class="upload-tip">图片大小不超过2M</div>
                <div class="upload-tip">仅支持上传PNG JPG JPEG类型图片</div>
              </div>
            </el-upload>
            
            <!-- 图片预览区域 -->
            <div v-if="executeForm.executionImage" class="image-preview">
              <img 
                :src="imagePreviewUrl" 
                alt="执行图片预览"
                class="preview-image"
                @load="handleImageLoad"
                @error="handleImageLoadError"
              />
              <div class="image-actions">
                <el-button type="primary" size="small" @click="reuploadImage">重新上传</el-button>
                <el-button type="danger" size="small" @click="removeImage">删除</el-button>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="执行记录" prop="executionRecord">
          <el-input
            v-model="executeForm.executionRecord"
            type="textarea"
            placeholder="请输入执行记录"
            :rows="3"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="executeDialogOpen = false">取消</el-button>
          <el-button type="primary" @click="submitExecute">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 改期对话框 -->
    <el-dialog title="改期任务" v-model="rescheduleDialogOpen" width="500px" append-to-body>
      <el-form ref="rescheduleRef" :model="rescheduleForm" :rules="rescheduleRules" label-width="120px">
        <el-form-item label="新的服务时间" prop="newServiceTime">
          <el-date-picker
            v-model="rescheduleForm.newServiceTime"
            type="datetime"
            placeholder="请选择新的服务时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rescheduleDialogOpen = false">取消</el-button>
          <el-button type="primary" @click="submitReschedule">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="arrangementRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="老人姓名" prop="elderlyId">
              <el-select
                v-model="form.elderlyId"
                placeholder="请选择老人"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in elderlyOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="护理项目" prop="projectNameId">
              <el-select
                v-model="form.projectNameId"
                placeholder="请选择护理项目"
                style="width: 100%"
                @change="handleProjectChange"
              >
                <el-option
                  v-for="item in nursingItemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select v-model="form.projectType" placeholder="请选择项目类型" style="width: 100%">
                <el-option label="护理计划内" value="护理计划内" />
                <el-option label="护理计划外" value="护理计划外" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="护理员" prop="executor">
              <el-select
                v-model="form.executor"
                placeholder="请选择护理员"
                style="width: 100%"
              >
                <el-option
                  v-for="item in caregiverOptions"
                  :key="item.userId"
                  :label="item.userName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="期望服务时间" prop="expectedServiceTime">
              <el-date-picker
                v-model="form.expectedServiceTime"
                type="datetime"
                placeholder="请选择期望服务时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联订单" prop="relatedOrderNo">
              <el-select
                v-model="form.relatedOrderNo"
                placeholder="请选择关联订单"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in orderOptions"
                  :key="item.orderNo"
                  :label="item.orderNo"
                  :value="item.orderNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注说明" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注说明"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Arrangement">
import { ref, reactive, toRefs, onMounted, getCurrentInstance, watch, nextTick } from 'vue'
import { listArrangementJoin, getArrangement, delArrangement, addArrangement, updateArrangement, exportArrangement, executeArrangement, cancelArrangement, rescheduleArrangement, getPcTodayPendingTasks } from "@/api/system/arrangement"
import { listElderly } from "@/api/system/elderly"
import { listItem } from "@/api/system/item"
import { listUser } from "@/api/system/user"
import { listOrderManagement } from "@/api/system/order"
import { useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user'

const router = useRouter()

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const arrangementList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 执行记录相关
const executeDialogOpen = ref(false)
const executeForm = ref({
  taskId: null,
  executionTime: null,
  executionImage: null,
  executionRecord: ''
})
const imagePreviewUrl = ref('')
const executeRules = ref({
  executionTime: [
    { required: true, message: "执行时间不能为空", trigger: "change" }
  ],
  executionImage: [
    { required: true, message: "执行图片不能为空", trigger: "change" }
  ],
  executionRecord: [
    { required: true, message: "执行记录不能为空", trigger: "blur" },
    { max: 100, message: "执行记录最多100个字符", trigger: "blur" }
  ]
})
const uploadUrl = ref('/dev-api/system/arrangement/upload')

// 改期对话框相关
const rescheduleDialogOpen = ref(false)
const rescheduleForm = ref({
  taskId: null,
  newServiceTime: null
})
const rescheduleRules = ref({
  newServiceTime: [
    { required: true, message: "新的服务时间不能为空", trigger: "change" }
  ]
})
const uploadHeaders = ref({
  'Authorization': 'Bearer ' + (localStorage.getItem('token') || '')
})

// 下拉选项数据
const elderlyOptions = ref([])
const nursingItemOptions = ref([])
const caregiverOptions = ref([])
const orderOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elderlyName: undefined,
    caregiverName: undefined,
    nursingItemName: undefined,
    expectedServiceTime: undefined,
    status: '待执行'  // 默认显示待执行tab
  },
  rules: {
    elderlyId: [
      { required: true, message: "老人姓名不能为空", trigger: "blur" }
    ],
    projectNameId: [
      { required: true, message: "护理项目不能为空", trigger: "blur" }
    ],
    projectType: [
      { required: true, message: "项目类型不能为空", trigger: "change" }
    ],
    executor: [
      { required: true, message: "护理员不能为空", trigger: "blur" }
    ],
    expectedServiceTime: [
      { required: true, message: "期望服务时间不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询任务安排列表 */
function getList() {
  console.log('========== getList() 被调用 ==========')
  loading.value = true
  
  // 构建查询参数，确保字段名与后端一致
  const searchParams = {
    pageNum: queryParams.value.pageNum || 1,
    pageSize: queryParams.value.pageSize || 10
  }
  
  // 只添加非空的搜索参数
  if (queryParams.value.elderlyName && queryParams.value.elderlyName.trim() !== '') {
    searchParams.elderly_name = queryParams.value.elderlyName.trim()
  }
  if (queryParams.value.caregiverName && queryParams.value.caregiverName.trim() !== '') {
    searchParams.caregiver_name = queryParams.value.caregiverName.trim()
  }
  if (queryParams.value.nursingItemName && queryParams.value.nursingItemName.trim() !== '') {
    searchParams.nursing_item_name = queryParams.value.nursingItemName.trim()
  }
  if (queryParams.value.status && queryParams.value.status.trim() !== '') {
    searchParams.status = queryParams.value.status.trim()
  }
  
  // 处理时间范围参数
  if (queryParams.value.expectedServiceTime && queryParams.value.expectedServiceTime.length === 2) {
    if (queryParams.value.expectedServiceTime[0]) {
      searchParams.beginTime = queryParams.value.expectedServiceTime[0]
    }
    if (queryParams.value.expectedServiceTime[1]) {
      searchParams.endTime = queryParams.value.expectedServiceTime[1]
    }
  }
  
  console.log('getList 查询参数:', searchParams)
  
  listArrangementJoin(searchParams).then(response => {
    console.log('API响应:', response)
    console.log('任务安排列表数据:', response.rows)
    console.log('数据字段检查:', response.rows.map(item => ({
      id: item.id,
      elderly_name: item.elderly_name,
      bed_no: item.bed_no,
      nursing_item_name: item.nursing_item_name,
      project_type: item.project_type,
      executor_name: item.executor_name,
      creator_name: item.creator_name,
      expected_service_time: item.expected_service_time,
      create_time: item.create_time,
      order_no: item.order_no,
      status: item.status
    })))
    
    arrangementList.value = response.rows || []
    total.value = response.total || 0
    loading.value = false
    
    // 显示数据统计
    console.log(`========== 查询结果 ==========`)
    console.log(`查询状态: ${searchParams.status || '全部'}`)
    console.log(`返回条数: ${response.rows?.length || 0}`)
    console.log(`总计条数: ${response.total || 0}`)
    console.log(`页面显示任务数: ${arrangementList.value.length}`)
    if (response.rows && response.rows.length > 0) {
      console.log(`任务执行人分布:`, response.rows.map(r => r.executor_name))
    }
  }).catch(error => {
    console.error('获取任务安排列表失败:', error)
    arrangementList.value = []
    total.value = 0
    loading.value = false
  })
}

/** 获取下拉选项数据 */
function getOptionsData() {
  console.log('开始获取下拉选项数据，当前queryParams:', queryParams.value)
  
  // 获取老人列表
  listElderly({ pageSize: 1000 }).then(response => {
    elderlyOptions.value = response.rows
    console.log('老人选项加载完成:', response.rows.length, '个')
  })
  
  // 获取护理项目列表
  listItem({ pageSize: 1000 }).then(response => {
    nursingItemOptions.value = response.rows
    console.log('护理项目选项加载完成:', response.rows.length, '个')
  })
  
  // 获取护理员列表
  listUser({ userType: 'caregiver', pageSize: 1000 }).then(response => {
    caregiverOptions.value = response.rows
    console.log('护理员选项加载完成:', response.rows.length, '个')
  })
  
  // 获取订单列表
  listOrderManagement({ pageSize: 1000 }).then(response => {
    orderOptions.value = response.rows.map(item => ({
      orderNo: item.order_no,
      orderStatus: item.order_status
    }))
    console.log('订单选项加载完成:', orderOptions.value.length, '个')
  })
}

/** 根据项目类型获取标签样式 */
function getProjectTypeStyle(projectType) {
  return projectType === '护理计划内' ? 'success' : 'warning'
}

/** 获取状态标签类型 */
function getStatusType(status) {
  const statusMap = {
    '待执行': 'warning',
    '已执行': 'success',
    '已取消': 'danger',
    '已完成': 'success'
  }
  return statusMap[status] || 'info'
}

/** 护理项目选择变化事件 */
function handleProjectChange(value) {
  const selectedItem = nursingItemOptions.value.find(item => item.id === value)
  if (selectedItem) {
    // 根据选择的护理项目自动设置项目类型
    const planItems = ['床上洗头', '协助更衣', '指甲护理']
    form.value.projectType = planItems.includes(selectedItem.name) ? '护理计划内' : '护理计划外'
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    elderlyId: null,
    projectNameId: null,
    projectType: null,
    expectedServiceTime: null,
    relatedOrderNo: null,
    executor: null,
    remark: null
  }
  proxy.resetForm("arrangementRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log('搜索按钮点击，当前查询参数:', queryParams.value)
  console.log('老人姓名:', queryParams.value.elderlyName)
  console.log('护理员姓名:', queryParams.value.caregiverName)
  console.log('护理项目:', queryParams.value.nursingItemName)
  console.log('任务状态:', queryParams.value.status)
  queryParams.value.pageNum = 1
  getList()
}

/** 分页操作 */
function handlePagination(pagination) {
  console.log('分页参数:', pagination)
  queryParams.value.pageNum = pagination.page
  queryParams.value.pageSize = pagination.limit
  getList()
}

/** 状态切换操作 */
function handleStatusChange(status) {
  console.log('状态切换:', status)
  queryParams.value.pageNum = 1
  getList()
}

/** 今日待执行任务 */
function handleTodayPending() {
  console.log('========== 开始查看今日待执行任务 ==========')
  loading.value = true
  
  const searchParams = {
    pageNum: queryParams.value.pageNum || 1,
    pageSize: queryParams.value.pageSize || 10
  }
  
  console.log('今日待执行查询参数:', searchParams)
  
  getPcTodayPendingTasks(searchParams).then(response => {
    console.log('今日待执行API响应:', response)
    
    if (response && response.rows) {
      console.log('今日待执行任务数据条数:', response.rows.length)
      console.log('今日待执行任务总数:', response.total)
      console.log('今日待执行任务数据:', response.rows)
      
      // 使用nextTick确保数据更新后再渲染
      proxy.$nextTick(() => {
        arrangementList.value = response.rows
        total.value = response.total || 0
        console.log('今日待执行任务列表更新完成，当前显示', arrangementList.value.length, '条，总共', total.value, '条')
      })
    } else {
      console.warn('今日待执行API响应格式异常:', response)
      arrangementList.value = []
      total.value = 0
    }
  }).catch(error => {
    console.error('获取今日待执行任务失败:', error)
    proxy.$modal.msgError('获取今日待执行任务失败: ' + (error.message || '未知错误'))
    arrangementList.value = []
    total.value = 0
  }).finally(() => {
    loading.value = false
    console.log('========== 今日待执行任务查询结束 ==========')
  })
}

/** 重置按钮操作 */
function resetQuery() {
  console.log('重置按钮点击')
  // 逐个重置属性，保持响应式
  queryParams.value.pageNum = 1
  queryParams.value.pageSize = 10
  queryParams.value.elderlyName = undefined
  queryParams.value.caregiverName = undefined
  queryParams.value.nursingItemName = undefined
  queryParams.value.expectedServiceTime = undefined
  queryParams.value.status = '待执行'  // 保持与初始化一致
  console.log('重置后的查询参数:', queryParams.value)
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加任务安排"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getArrangement(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改任务安排"
  })
}

/** 查看按钮操作 */
function handleView(row) {
  // 根据任务状态跳转到对应的详情页面
  const routeMap = {
    '待执行': '/service/arrangement-detail-pending',
    '已执行': '/service/arrangement-detail-executed',
    '已取消': '/service/arrangement-detail-cancelled'
  }
  
  const routePath = routeMap[row.status] || '/service/arrangement-detail-pending'
  
  // 使用路由跳转到对应的详情页
  router.push({
    path: routePath,
    query: { id: row.id }
  })
}
/** 执行按钮操作 */
function handleExecute(row) {
  // 重置执行表单
  executeForm.value = {
    taskId: row.id,
    executionTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
    executionImage: null,
    executionRecord: ''
  }
  executeDialogOpen.value = true
}

/** 取消按钮操作 */
function handleCancel(row) {
  proxy.$modal.prompt('请输入取消原因', '取消任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s.,!?;:\"'，。？！；：""''（）()【】\[\]《》<>]{1,100}$/,
    inputErrorMessage: '取消原因不能为空，且不能包含表情符号，最多输入100个字符',
    inputAttrs: {
      maxlength: 100,
      placeholder: '请输入取消原因（最多100个字符，不能包含表情符号）'
    }
  }).then(({ value }) => {
    const cancelData = {
      id: row.id,
      status: '已取消',
      cancelReason: value,
      cancelTime: new Date(),
      cancelPerson: userStore.id
    }
    cancelArrangement(cancelData).then(() => {
      proxy.$modal.msgSuccess("取消成功")
      getList()
    })
  }).catch(() => {
    proxy.$modal.msgError("取消操作已中断")
  })
}

/** 改期按钮操作 */
function handleReschedule(row) {
  // 重置表单
  rescheduleForm.value = {
    taskId: row.id,
    newServiceTime: row.expected_service_time || null
  }
  rescheduleDialogOpen.value = true
  
  // 下次DOM更新后重置表单验证
  nextTick(() => {
    proxy.$refs.rescheduleRef?.clearValidate()
  })
}

/** 提交改期 */
function submitReschedule() {
  proxy.$refs.rescheduleRef.validate(valid => {
    if (valid) {
      const rescheduleData = {
        id: rescheduleForm.value.taskId,
        expectedServiceTime: rescheduleForm.value.newServiceTime,
        rescheduleTime: new Date()
      }
      
      rescheduleArrangement(rescheduleData).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("改期成功")
          rescheduleDialogOpen.value = false
          getList()
        } else {
          proxy.$modal.msgError(response.msg || "改期失败")
        }
      }).catch(error => {
        console.error('改期失败:', error)
        proxy.$modal.msgError("改期失败")
      })
    }
  })
}

/** 图片上传前验证 */
function beforeImageUpload(file) {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    proxy.$modal.msgError('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    proxy.$modal.msgError('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/** 图片上传成功回调 */
function handleImageSuccess(response) {
  console.log('上传响应:', response)
  if (response.code === 200) {
    // 后端返回的数据结构：{ url: '/static/uploads/xxx.png', fileName: 'xxx.png' }
    let imageUrl = response.data?.url || response.url || response.data
    const fileName = response.data?.fileName || response.fileName
    console.log('从响应中提取的图片URL:', imageUrl)
    console.log('从响应中提取的文件名:', fileName)

    // 规范化为可访问的完整URL（前端运行在80端口，静态资源在8080端口）
    if (imageUrl && !imageUrl.startsWith('http')) {
      if (imageUrl.startsWith('/uploads/')) {
        imageUrl = `http://localhost:8080${imageUrl}`
      } else if (imageUrl.startsWith('/static/')) {
        imageUrl = `http://localhost:8080${imageUrl}`
      } else if (!imageUrl.startsWith('/')) {
        imageUrl = `http://localhost:8080/uploads/${imageUrl}`
      } else {
        imageUrl = `http://localhost:8080${imageUrl}`
      }
    }

    console.log('设置前的executeForm.executionImage:', executeForm.value.executionImage)
    executeForm.value.executionImage = imageUrl
    executeForm.value.imageFileName = fileName
    console.log('设置后的executeForm.executionImage:', executeForm.value.executionImage)
    console.log('完整的executeForm:', executeForm.value)
    proxy.$modal.msgSuccess('图片上传成功')
    
    // 直接使用图片URL进行预览
    imagePreviewUrl.value = imageUrl
    console.log('设置图片预览URL:', imageUrl)
  } else {
    proxy.$modal.msgError('图片上传失败: ' + (response.msg || '未知错误'))
  }
}

/** 图片上传失败回调 */
function handleImageError(error) {
  console.error('图片上传失败:', error)
  proxy.$modal.msgError('图片上传失败')
}

/** 获取完整图片URL */
function getFullImageUrl(imageUrl) {
  console.log('getFullImageUrl 输入:', imageUrl)
  if (!imageUrl) {
    console.log('图片URL为空，返回空字符串')
    return ''
  }
  if (imageUrl.startsWith('http')) {
    console.log('图片URL已经是完整URL:', imageUrl)
    return imageUrl
  }
  
  // 修复：对于/static/开头的URL，使用专门的图片获取接口返回Base64数据
  if (imageUrl.startsWith('/static/')) {
    const filename = imageUrl.replace('/static/uploads/', '')
    console.log('需要获取Base64图片数据:', filename)
    // 这里需要异步获取Base64数据，暂时返回原URL
    return imageUrl
  }
  
  // 其他情况使用当前域名
  const fullUrl = window.location.origin + imageUrl
  console.log('构建完整URL:', fullUrl)
  return fullUrl
}

/** 重新上传图片 */
function reuploadImage() {
  executeForm.value.executionImage = null
}

/** 删除图片 */
function removeImage() {
  executeForm.value.executionImage = null
}

/** 图片加载成功 */
function handleImageLoad() {
  console.log('图片加载成功')
}

/** 图片加载失败 */
function handleImageLoadError(event) {
  console.error('图片加载失败:', event)
  // 尝试一次后端直连接口作为兜底
  if (executeForm.value?.imageFileName) {
    const fallbackUrl = `http://localhost:8080/system/arrangement/image/${executeForm.value.imageFileName}`
    console.log('尝试备用URL:', fallbackUrl)
    imagePreviewUrl.value = fallbackUrl
    executeForm.value.executionImage = fallbackUrl
  } else {
    proxy.$modal.msgError('图片加载失败')
  }
}

/** 获取Base64图片数据 */
async function loadImageAsBase64(imageUrl) {
  try {
    if (!imageUrl || !imageUrl.startsWith('/static/')) {
      return imageUrl
    }
    
    const filename = imageUrl.replace('/static/uploads/', '')
    console.log('获取Base64图片数据:', filename)
    
    const response = await fetch(`/system/arrangement/image/${filename}`)
    const result = await response.json()
    
    if (result.code === 200 && result.data && result.data.data) {
      console.log('成功获取Base64图片数据')
      return result.data.data
    } else {
      console.error('获取Base64图片数据失败:', result.msg)
      return imageUrl
    }
  } catch (error) {
    console.error('获取Base64图片数据异常:', error)
    return imageUrl
  }
}

/** 提交执行记录 */
function submitExecute() {
  proxy.$refs["executeRef"].validate(valid => {
    if (valid) {
      const executeData = {
        id: executeForm.value.taskId,
        status: '已执行',
        executor: userStore.id,  // 添加当前登录用户ID作为执行人
        executionTime: executeForm.value.executionTime,
        executionImage: executeForm.value.executionImage,
        executionRecord: executeForm.value.executionRecord
      }
      executeArrangement(executeData).then(() => {
        proxy.$modal.msgSuccess("执行成功")
        executeDialogOpen.value = false
        getList()
        // 执行成功后跳转到详情页面
        setTimeout(() => {
          console.log('准备跳转到详情页面，任务ID:', executeForm.value.taskId)
          console.log('当前路由:', router.currentRoute.value)
          console.log('路由实例:', router)
          
          // 先尝试直接跳转
          try {
            router.push({
              path: '/service/arrangement-detail-executed',
              query: { id: executeForm.value.taskId }
            }).then(() => {
              console.log('跳转成功')
            }).catch(error => {
              console.error('跳转失败:', error)
              proxy.$modal.msgError('跳转到详情页面失败: ' + error.message)
            })
          } catch (error) {
            console.error('路由跳转异常:', error)
            proxy.$modal.msgError('路由跳转异常: ' + error.message)
          }
        }, 1000) // 延迟1秒跳转，让用户看到成功提示
      })
    }
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["arrangementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateArrangement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addArrangement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除选中的任务安排？').then(function() {
    return delArrangement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  const params = {
    ...queryParams.value,
    elderly_name: queryParams.value.elderlyName,
    caregiver_name: queryParams.value.caregiverName,
    nursing_item_name: queryParams.value.nursingItemName
  }
  
  // 处理日期范围
  if (params.expectedServiceTime && params.expectedServiceTime.length === 2) {
    params.beginTime = params.expectedServiceTime[0]
    params.endTime = params.expectedServiceTime[1]
  }
  
  delete params.elderlyName
  delete params.caregiverName
  delete params.nursingItemName
  delete params.expectedServiceTime
  
  loading.value = true
  exportArrangement(params).then(response => {
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `任务安排_${new Date().getTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    loading.value = false
  }).catch(error => {
    loading.value = false
    proxy.$modal.msgError("导出失败")
  })
}

// 初始化
// 监控executeForm.executionImage的变化
watch(() => executeForm.value.executionImage, (newVal, oldVal) => {
  console.log('executeForm.executionImage 变化:', {
    oldValue: oldVal,
    newValue: newVal,
    timestamp: new Date().toISOString()
  })
  
  if (newVal) {
    imagePreviewUrl.value = newVal
    console.log('设置图片预览URL:', newVal)
  } else {
    imagePreviewUrl.value = ''
  }
}, { deep: true })

// 监控queryParams的变化
watch(() => queryParams.value, (newVal, oldVal) => {
  console.log('queryParams 变化:', {
    oldValue: oldVal,
    newValue: newVal,
    timestamp: new Date().toISOString()
  })
}, { deep: true })

onMounted(() => {
  console.log('页面挂载，初始化queryParams:', queryParams.value)
  getOptionsData()
  getList()
})
</script>

<style scoped lang="scss">
/* 页面整体样式 */
.task-arrangement-page {
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  /* 搜索容器 */
  .search-container {
    background: #fff;
    padding: 20px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);

    .search-form {
      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #333;
      }

      .form-buttons {
        display: flex;
        justify-content: flex-end;

        :deep(.el-form-item__content) {
          justify-content: flex-end;
        }

        .el-button {
          min-width: 80px;
        }

        .search-btn {
          margin-left: 12px;
        }
      }

      .search-select,
      .search-date-picker {
        width: 100%;
      }
    }
  }

  /* 工具栏 */
  .toolbar-row {
    background: #fff;
    padding: 16px 20px;
    margin-bottom: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    align-items: center;

    .status-radio-group {
      :deep(.el-radio-button__inner) {
        padding: 10px 20px;
        font-weight: 500;
        border-color: #00CC99;
      }

      :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
        background-color: #00CC99;
        border-color: #00CC99;
        box-shadow: -1px 0 0 0 #00CC99;
      }
    }

    .action-btn {
      margin-left: 12px;
      font-weight: 500;
    }

    .text-right {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 8px;
    }
  }

  /* 表格样式 */
  .task-arrangement-table {
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    :deep(.el-table__header) {
      th {
        background: #f5f7fa;
        color: #333;
        font-weight: 600;
        font-size: 14px;
        padding: 16px 0;
      }
    }

    :deep(.el-table__body) {
      td {
        padding: 14px 0;
        font-size: 14px;
        color: #606266;
      }

      .el-table__row:hover {
        background-color: #f5f7fa;
      }
    }

    .text-muted {
      color: #909399;
    }

    /* 操作按钮样式 */
    :deep(.el-button--text) {
      padding: 4px 8px;
      margin: 0 4px;
    }
  }

  /* 数据统计 */
  .data-stats {
    margin-top: 20px;

    :deep(.el-alert) {
      border-radius: 8px;
      background: #fff;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
    }
  }
}

/* 分页样式 */
:deep(.task-arrangement-pagination) {
  margin-top: 20px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
  justify-content: center;
}

/* 通用样式 */
.text-right {
  text-align: right;
}

.mb8 {
  margin-bottom: 8px;
}

/* 输入框获取焦点时的样式 */
:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus),
:deep(.el-select .el-input__inner:focus) {
  border-color: #00CC99;
  box-shadow: 0 0 0 2px rgba(0, 204, 153, 0.1);
}

/* 今日待执行按钮样式 - 原始绿色系 */
.today-pending-btn {
  background: linear-gradient(135deg, #52c41a 0%, #95de64 100%) !important;
  border: none !important;
  color: white !important;
  box-shadow: 0 3px 15px 0 rgba(82, 196, 26, 0.4);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600 !important;
  position: relative;
  overflow: hidden;
}

.today-pending-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.today-pending-btn:hover::before {
  left: 100%;
}

.today-pending-btn:hover {
  background: linear-gradient(135deg, #73d13d 0%, #b7eb8f 100%) !important;
  transform: translateY(-3px);
  box-shadow: 0 6px 20px 0 rgba(82, 196, 26, 0.6);
}

.today-pending-btn:active {
  transform: translateY(-1px);
  box-shadow: 0 2px 10px 0 rgba(82, 196, 26, 0.5);
}

/* 图片上传容器样式 */
.image-upload-container {
  width: 100%;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  height: 180px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 16px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-bottom: 4px;
}

/* 图片预览样式 */
.image-preview {
  position: relative;
  width: 100%;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.image-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.image-actions .el-button {
  margin: 0;
}

.form-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 8px;
}

.reset-btn {
  background-color: #ffffff;
  border: 1px solid #d9d9d9;
  color: #000000;
}

.search-btn {
  background-color: #00CC99; 
  border: none;
  color: #ffffff;
}

.text-muted {
  color: #909399;
}

.text-right {
  text-align: right;
}

.mb8 {
  margin-bottom: 8px;
}

/* 调整间距为第二张图片样式 */
.app-container {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-row {
  margin-bottom: 16px;
}

.el-table {
  margin-top: 16px;
}

/* 执行记录弹窗样式 */
.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  width: 100%;
  height: 120px;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 28px;
  height: 28px;
  line-height: 120px;
  margin: 0 auto;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-top: 10px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-form-container {
    padding: 15px;
  }
  
  .search-form .el-col {
    margin-bottom: 10px;
  }
}
</style>